package org.halk.es.crawl.utils;

import org.halk.es.crawl.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

/**
 * 获取jd搜索页面
 *
 * @Author halk
 * @Date 2023/3/3 10:26
 **/
@Component
public class HtmlParseUtil {

    public ArrayList<Content> parseJD(String keywords) throws IOException {
        String url = "https://search.jd.com/Search?keyword=" + keywords.trim();
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");

        ArrayList<Content> result = new ArrayList<>();
        for (Element el : elements) {
            String imgUrl = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String priceStr = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            double price = 0;
            try {
                System.out.println(priceStr);
                price = Double.parseDouble(priceStr.split("￥")[1].substring(1).trim());
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.add(
                    new Content()
                            .setTitle(title)
                            .setPrice(price)
                            .setImgUrl(imgUrl)
            );
        }

        return result;
    }
}
